package com.alog.javaee.day41;



import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
    private UserDao dao = new UserDaoImpl();

    @Override
    public List<User> findAll() {
        //调用Dao完成查询
        return dao.findAll();
    }

    @Override
    public User login(User user) {
        return dao.login(user);
    }

    @Override
    public void add(User user) {
        dao.add(user);
    }

    @Override
    public void delete(String id) {
        dao.delete(Integer.valueOf(id));
    }

    @Override
    public User finUserById(String id) {
        return dao.findById(Integer.valueOf(id));
    }

    @Override
    public void update(User user) {
        dao.update(user);
    }

    @Override
    public void deleteSelected(String[] ids) {
        if(ids != null && ids.length > 0){
            for(String id : ids){
                dao.delete(Integer.valueOf(id));
            }
        }
    }

    @Override
    public PageBean<User> findUserByPage(String currentPage, Map<String, String[]> condition) {
        int currPage = Integer.valueOf(currentPage);
        PageBean<User> pb = new PageBean<>();
        if(currPage <= 0){
            currPage = 1;
        }


        pb.setPageSize(PageBean.PAGE_SIZE);

        int totalCount = dao.findTotalCount(condition);
        pb.setTotalCount(totalCount);

        int pages = 0;
        if(totalCount % PageBean.PAGE_SIZE == 0){
            pages = totalCount / PageBean.PAGE_SIZE;
        } else {
            pages = totalCount / PageBean.PAGE_SIZE + 1;
        }
        pb.setTotalPages(pages);
        if(currPage > pages){
            currPage = pages;
        }
        pb.setCurrentPage(currPage);

        if(currPage <= 0){
            currPage = 1;
        }
        List<User> list = dao.findByPage((currPage - 1) * PageBean.PAGE_SIZE, PageBean.PAGE_SIZE, condition);
        pb.setList(list);



        return pb;
    }
}
